#pragma once

#include <iostream>
#include <unistd.h>
#include <memory.h>
#include <string>
#include <sys/wait.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "log.hpp"

class Sock
{
private:
    const static int g_backlog = 10; // 一般不太大也不太小

public:
    Sock() {}
    // 1、创建套接字
    static int Socket()
    {
        int listen_sock = socket(AF_INET, SOCK_STREAM, 0); // SOCK_STREAM:流式套接的套接字类型
        if (listen_sock < 0)
        {
            logMessage(FATAL, "create socket error,%d: %s", errno, strerror(errno));
            exit(2);
        }
        logMessage(NORMAL, "create socket success, sock: %d", listen_sock); // 流式套接字和文件流一样，0 1 2是打开的
        return listen_sock;
    }
    // 2、绑定
    static int Bind(int sock, uint16_t port, std::string ip = "0.0.0.0")
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &local.sin_addr);
        if (bind(sock, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            logMessage(FATAL, "bind error,%d: %s", errno, strerror(errno));
            exit(3);
        }
    }
    // 建立连接
    static void Listen(int sock)
    {
        // 3、TCP是面向连接的，当正式通信时需要先建立连接
        if (listen(sock, g_backlog) < 0)
        {
            logMessage(FATAL, "listen error,%d: %s", errno, strerror(errno));
            exit(4);
        }

        logMessage(NORMAL, "init server success");
    }

    static int Accpet(int listensock, std::string *ip, uint16_t *port) // 4、获取连接
    {

        struct sockaddr_in src;
        socklen_t len = sizeof(src);
        int service_sock = accept(listensock, (struct sockaddr *)&src, &len);
        if (service_sock < 0)
        {
            logMessage(ERROR, "accpet error,%d: %s", errno, strerror(errno));
            return -1;
        }
        if (port)
            *port = ntohs(src.sin_port);
        if (ip)
            *ip = inet_ntoa(src.sin_addr);

        return service_sock;
    }

    static bool Connect(int sock, const std::string &server_ip, const uint16_t &server_port)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(server_port);
        server.sin_addr.s_addr = inet_addr(server_ip.c_str());

        if (!connect(sock, (struct sockaddr *)&server, sizeof(server)))
            return true;
        else
            return false;
    }

    ~Sock()
    {
    }
};